#!/usr/bin/env python
# coding:utf8


'''cncert cluster platform interface stuff

@author: will
@date: 13-5-7
@version: $1.0.0$
'''


import base64
import sys
from hashlib import  md5
from xml.dom import minidom

from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import

from config import ws_uri, app_reg_dict, resource_require_xml, app_id_filename, app_rec_dict


def main():
	opts, parser = _opt()

	try:
		if opts.reg_app:
			reg_app()
		elif opts.add_task:
			run_app()
		else:
			parser.print_help()
	except Exception, e:
		print(e)
	

def reg_app():
	'''reg app

	@note: register(xs:string appName, xs:string appDisplayName,\
			appFileArray apps, xs:string username, xs:string password, )
	'''
	client = _get_ws(ws_uri)

	zip_fobj = file('crawler.tgz', 'rb').read()
	s_fobj = file('job.py', 'rb').read()

	# create complex argument
	apps = client.factory.create('appFileArray')
	app_f = client.factory.create('appFile')

	app_f.appContent = _base64_e(zip_fobj)
	app_f.appFileMd5Value = md5(zip_fobj).hexdigest()
	app_f.appFileName = 'crawler.tgz'
	app_f.scriptContent = _base64_e(s_fobj)
	app_f.scriptMd5Value = md5(s_fobj).hexdigest()
	app_f.scriptFileName = 'job.py'
	app_f.resourceRequire = resource_require_xml

	apps.item.append(app_f)
	app_reg_dict['apps'] = apps
	
	ret = client.service.register(**app_reg_dict)

	# parse ws's return, if success write app-id to file 'app_id'
	try:
		dom = minidom.parseString(ret)
		name = dom.getElementsByTagName('name')[0].lastChild.nodeValue
		value = dom.getElementsByTagName('value')[0].lastChild.nodeValue

		if name == 'success':
			f_obj = file(app_id_filename, 'w')
			f_obj.write('%s' % value)
			f_obj.close()
			print('%s: %s' % (name, value))
		else:
			print('register error:\n    %s' % value)
	except Exception, e:
		print('reg got exception: %s' % e)
		print('original info:\n    %s' % ret)


def run_app():
	'''run app

	@note: submit(xs:string appId, xs:string userJobId, xs:string parameter,\
			xs:string resultAddress, xs:int jobPriority, xs:int copyNumber, \
			xs:long budgetRunTime, xs:int resourceProvince, xs:int ispName, \
			xs:string bandwidth, xs:string username, xs:string password, )
	'''
	client = _get_ws(ws_uri)

	try:
		app_id = file(app_id_filename, 'r').read()
	except IOError, e:
		print('can not find file: %s, not registed yet?' % app_id_filename)
		sys.exit(12)

	param_xml_str = '''<?xml version="1.0" encoding="UTF-8"?>
<parameters>
	<parameter>
		<content>%s</content>
	</parameter>
</parameters>
''' % file('urls.txt').read()

	app_rec_dict['parameter'] = param_xml_str
	app_rec_dict['appId'] = app_id
	print app_rec_dict

	# create complex argument
	ret = client.service.submit(**app_rec_dict)

	# parse ws's return, if success write app-id to file 'app-id'
	try:
		c = '''
		dom = minidom.parseString(ret)
		name = dom.getElementsByTagName('name')[0].lastChild.nodeValue
		value = dom.getElementsByTagName('value')[0].lastChild.nodeValue

		if name == 'success':
			f_obj = file(value, 'w')
			f_obj.write('%s\n' % value)
			f_obj.close()
			print('%s: %s' % (name, value))
		else:
			print('register error:\n    %s' % value)
			'''
		print ret
	except Exception, e:
		print('run app got exception: %s' % e)
		print('original info:\n    %s' % ret)


def _base64_e(txt):
	return base64.encodestring(txt)


def _get_ws(uri, imp_uri=None, imp_location=None, imp_filter=None):
	if imp_uri:
		imp = Import(uri, location=imp_location)
		imp.filter.add(imp_filter)
		d = ImportDoctor(imp)

		client = Client(uri, doctor=d)
	else:
		client = Client(uri)
	
	return client
	

def _opt():
	from optparse import OptionParser  
	parser = OptionParser('%prog :  \n\
	python cluster_tools.py -r/-a')  

	parser.add_option('-r', '--reg_app', dest='reg_app',  
					  action='store_true',
					  default=False,
					  help='reg app switch.')  

	parser.add_option('-a', '--add_task', dest='add_task',  
					  action='store_true',
					  default=False,
					  help='add task switch.')  

	(options, args) = parser.parse_args() 	

	return options, parser


if __name__ == '__main__':
	main()
